<template>
	<view>
		<!-- 顶部导航栏 -->
		<cu-custom bgColor="bg-gradual-green" :isBack="true">
			<block slot="content">我的头像</block>
		</cu-custom>
		<message ref="message"></message>
		
		<!-- 头像区 -->
		<view class="bg-img" :style="{'background-image':'url('+ avatar +')'}" style="height: 600rpx; margin-bottom: 40rpx;" />
		<view class="cu-bar bg-white foot">
			<view class="action margin-0 flex-sub  solid-left" @click="handleUpload">上传</view>
			<view class="action margin-0 flex-sub  solid-left" @click="handleBack">返回</view>
		</view>

	</view>
</template>

<script>
	import setting from '@/settings.js'
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				imageStyles: {
					height: 64
				},
				setting
			}
		},
		computed: {
			...mapGetters(['avatar']),
		},
		methods: {
			handleBack() {
				uni.navigateBack()
			},
			handleUpload() {
				const _this = this

				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						_this.uploadAvatar(res.tempFilePaths[0])
					}
				});
			},
			// 上传头像函数
			uploadAvatar(filePath) {
				const _this = this
				// 设置请求头
				const header = {}
				if (this.$store.getters.token) {
					header.Authorization = this.$store.getters.token
				}
				uni.uploadFile({
					url: _this.setting.avatarUploadURL,
					filePath: filePath,
					header: header,
					name: 'file',
					success: (res) => {
						const data = JSON.parse(res.data)
						if(data.code == 200) {
							const avatar = data.data
							_this.$store.dispatch('user/setAvatar', avatar)
							_this.$refs.message.success({
								title: '上传成功！',
								duration: 2000
							})
						} else {
							_this.$refs.message.error({
								title: data.msg,
								duration: 2000
							})
						}
					}
				});
			}
		}
	}
</script>

<style>

</style>
